package com.example.ysdt.service.impl;

import com.example.ysdt.service.FileService;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    public String uploadImage(MultipartFile file, String folder){
        if (file == null) {
            return  "请选择要上传的图片";
        }
        if (file.getSize() > 1024 * 1024 * 5) {
            return "文件大小不能大于5M";
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return "请选择jpg,jpeg,gif,png格式的图片";
        }
        // 设置保存路径
        File savePathFile = new File(folder);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdirs();
        }
        //通过UUID生成唯一文件名
        String filename = UUID.randomUUID().toString().replaceAll("-","") + "." + suffix;
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(folder + filename));
            return folder + filename;
        } catch (Exception e) {
            e.printStackTrace();
            return "保存文件异常";
        }
    }
}
